/**
 * 需求创建/编辑表单JavaScript
 * 负责表单交互、文档管理、数据验证和提交
 */

// 全局变量
let isEditMode = false;
let currentRequirementId = null;
let documents = [];
let projects = [];
let developers = [];
let formData = {};
let lastSavedTime = null;
let isDirty = false;

// DOM元素
const elements = {
    // 表单相关
    form: document.getElementById('requirementForm'),
    title: document.getElementById('title'),
    projectId: document.getElementById('projectId'),
    priority: document.getElementById('priority'),
    ownerId: document.getElementById('ownerId'),
    expectedCompletionDate: document.getElementById('expectedCompletionDate'),
    description: document.getElementById('description'),
    
    // 页面元素
    pageTitle: document.getElementById('pageTitle'),
    breadcrumbTitle: document.getElementById('breadcrumbTitle'),
    submitBtn: document.getElementById('submitBtn'),
    submitText: document.getElementById('submitText'),
    
    // 文档相关
    documentsList: document.getElementById('documentsList'),
    noDocuments: document.getElementById('noDocuments'),
    addDocumentBtn: document.getElementById('addDocumentBtn'),
    addDocumentModal: document.getElementById('addDocumentModal'),
    addDocumentForm: document.getElementById('addDocumentForm'),
    saveDocumentBtn: document.getElementById('saveDocumentBtn'),
    
    // 状态面板
    formStatus: document.getElementById('formStatus'),
    lastSaved: document.getElementById('lastSaved'),
    documentCount: document.getElementById('documentCount'),
    
    // 操作按钮
    // 已移除的按钮元素选择器
    loadTemplateBtn: document.getElementById('loadTemplateBtn'),
    importDocBtn: document.getElementById('importDocBtn'),
    exportDraftBtn: document.getElementById('exportDraftBtn'),
    
    // 预览相关
    // previewModal和previewContent已移除
    // previewSubmitBtn已移除
    
    // Toast通知
    successToast: document.getElementById('successToast'),
    errorToast: document.getElementById('errorToast'),
    infoToast: document.getElementById('infoToast'),
    successMessage: document.getElementById('successMessage'),
    errorMessage: document.getElementById('errorMessage'),
    infoMessage: document.getElementById('infoMessage'),
    
    // 其他
    loadingOverlay: document.getElementById('loadingOverlay')
};

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
    bindEvents();
    loadInitialData();
});

/**
 * 初始化页面
 */
function initializePage() {
    // 检查是否为编辑模式
    // 从路径中提取需求ID: /requirements/{id}/edit
    const pathParts = window.location.pathname.split('/');
    if (pathParts.length >= 3 && pathParts[1] === 'requirements' && pathParts[3] === 'edit') {
        currentRequirementId = pathParts[2];
        isEditMode = true;
    } else {
        // 兼容查询参数方式
        const urlParams = new URLSearchParams(window.location.search);
        currentRequirementId = urlParams.get('id');
        isEditMode = !!currentRequirementId;
    }
    
    // 更新页面标题和按钮文本
    if (isEditMode) {
        updatePageForEditMode();
    }
    
    // 初始化Bootstrap组件
    initializeBootstrapComponents();
    
    // 设置表单变更监听
    setupFormChangeTracking();
    
    // 设置自动保存
    setupAutoSave();
}

/**
 * 更新页面为编辑模式
 */
function updatePageForEditMode() {
    if (elements.pageTitle) {
        elements.pageTitle.innerHTML = '<i class="bi bi-pencil-square"></i> 编辑需求';
    }
    if (elements.breadcrumbTitle) {
        elements.breadcrumbTitle.textContent = '编辑需求';
    }
    if (elements.submitText) {
        elements.submitText.textContent = '保存修改';
    }
    if (elements.formStatus) {
        elements.formStatus.textContent = '编辑中';
    }
    
    // 在编辑模式下禁用不可修改的字段
    if (elements.projectId) {
        elements.projectId.disabled = true;
        elements.projectId.style.backgroundColor = '#f8f9fa';
        elements.projectId.title = '项目归属不可修改';
        const projectIdHelp = document.getElementById('projectIdHelp');
        if (projectIdHelp) projectIdHelp.style.display = 'block';
    }
    if (elements.ownerId) {
        elements.ownerId.disabled = true;
        elements.ownerId.style.backgroundColor = '#f8f9fa';
        elements.ownerId.title = '负责人变更需要专门的流程';
        const ownerIdHelp = document.getElementById('ownerIdHelp');
        if (ownerIdHelp) ownerIdHelp.style.display = 'block';
    }
    if (elements.expectedCompletionDate) {
        elements.expectedCompletionDate.disabled = true;
        elements.expectedCompletionDate.style.backgroundColor = '#f8f9fa';
        elements.expectedCompletionDate.title = '期望完成日期不可修改';
        const expectedCompletionDateHelp = document.getElementById('expectedCompletionDateHelp');
        if (expectedCompletionDateHelp) expectedCompletionDateHelp.style.display = 'block';
    }
    
    // 显示编辑模式下的快速保存按钮，隐藏底部的原始保存按钮
    const editModeActions = document.getElementById('editModeActions');
    const formActions = document.querySelector('.form-actions');
    if (editModeActions) {
        editModeActions.style.display = 'block';
    }
    if (formActions) {
        formActions.style.display = 'none';
    }
}

/**
 * 初始化Bootstrap组件
 */
function initializeBootstrapComponents() {
    // 初始化模态框
    if (elements.addDocumentModal) {
        new bootstrap.Modal(elements.addDocumentModal);
    }
    if (elements.previewModal) {
        new bootstrap.Modal(elements.previewModal);
    }
    
    // 初始化Toast
    ['successToast', 'errorToast', 'infoToast'].forEach(toastId => {
        const toastElement = elements[toastId];
        if (toastElement) {
            new bootstrap.Toast(toastElement);
        }
    });
}

/**
 * 设置表单变更跟踪
 */
function setupFormChangeTracking() {
    if (!elements.form) return;
    
    const formElements = elements.form.querySelectorAll('input, select, textarea');
    formElements.forEach(element => {
        element.addEventListener('input', markFormAsDirty);
        element.addEventListener('change', markFormAsDirty);
    });
    
    // 监听页面离开事件
    window.addEventListener('beforeunload', function(e) {
        if (isDirty) {
            e.preventDefault();
            e.returnValue = '您有未保存的更改，确定要离开吗？';
            return e.returnValue;
        }
    });
}

/**
 * 设置自动保存
 */
function setupAutoSave() {
    // 自动保存功能已移除
}

/**
 * 绑定事件
 */
function bindEvents() {
    // 表单提交
    if (elements.form) {
        elements.form.addEventListener('submit', handleFormSubmit);
    }
    
    // 文档相关事件
    if (elements.addDocumentBtn) {
        elements.addDocumentBtn.addEventListener('click', showAddDocumentModal);
    }
    if (elements.saveDocumentBtn) {
        elements.saveDocumentBtn.addEventListener('click', saveDocument);
    }
    if (elements.addDocumentForm) {
        elements.addDocumentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveDocument();
        });
    }
    
    // 操作按钮事件
    // 已移除按钮的事件绑定
    
    // 快捷操作事件
    if (elements.loadTemplateBtn) {
        elements.loadTemplateBtn.addEventListener('click', loadTemplate);
    }
    if (elements.importDocBtn) {
        elements.importDocBtn.addEventListener('click', importDocuments);
    }
    if (elements.exportDraftBtn) {
        elements.exportDraftBtn.addEventListener('click', exportDraft);
    }
}

/**
 * 加载初始数据
 */
async function loadInitialData() {
    try {
        showLoading(true);
        
        // 并行加载基础数据
        await Promise.all([
            loadProjects(),
            loadDevelopers()
        ]);
        
        // 如果是编辑模式，加载需求数据
        if (isEditMode) {
            await loadRequirementData();
        }
        
        // 更新状态显示
        updateStatusDisplay();
        
    } catch (error) {
        console.error('加载初始数据失败:', error);
        showError('加载数据失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

/**
 * 加载项目列表
 */
async function loadProjects() {
    try {
        const response = await fetch('/api/projects');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        projects = await response.json();
        populateProjectSelect();
        
    } catch (error) {
        console.warn('加载项目列表失败:', error);
        projects = [];
    }
}

/**
 * 加载开发者列表
 */
async function loadDevelopers() {
    try {
        const response = await fetch('/api/developers');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        developers = await response.json();
        populateDeveloperSelect();
        
    } catch (error) {
        console.warn('加载开发者列表失败:', error);
        developers = [];
    }
}

/**
 * 加载需求数据（编辑模式）
 */
async function loadRequirementData() {
    try {
        const response = await fetch(`/api/requirements/${currentRequirementId}`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const requirement = await response.json();
        populateForm(requirement);
        
        // 加载文档
        await loadDocuments();
        
    } catch (error) {
        console.error('加载需求数据失败:', error);
        showError('加载需求数据失败: ' + error.message);
    }
}

/**
 * 加载文档列表
 */
async function loadDocuments() {
    try {
        const response = await fetch(`/api/requirements/${currentRequirementId}/documents`);
        if (!response.ok) {
            if (response.status === 404) {
                documents = [];
                renderDocuments();
                return;
            }
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        documents = await response.json();
        renderDocuments();
        
    } catch (error) {
        console.warn('加载文档失败:', error);
        documents = [];
        renderDocuments();
    }
}

/**
 * 填充项目选择框
 */
function populateProjectSelect() {
    if (!elements.projectId) return;
    
    // 清空现有选项（保留默认选项）
    const defaultOption = elements.projectId.querySelector('option[value=""]');
    elements.projectId.innerHTML = '';
    if (defaultOption) {
        elements.projectId.appendChild(defaultOption);
    }
    
    // 添加项目选项
    projects.forEach(project => {
        const option = document.createElement('option');
        option.value = project.id;
        option.textContent = project.name;
        elements.projectId.appendChild(option);
    });
}

/**
 * 填充开发者选择框
 */
function populateDeveloperSelect() {
    if (!elements.ownerId) return;
    
    // 清空现有选项（保留默认选项）
    const defaultOption = elements.ownerId.querySelector('option[value=""]');
    elements.ownerId.innerHTML = '';
    if (defaultOption) {
        elements.ownerId.appendChild(defaultOption);
    }
    
    // 添加开发者选项
    developers.forEach(developer => {
        const option = document.createElement('option');
        option.value = developer.id;
        option.textContent = developer.name;
        elements.ownerId.appendChild(option);
    });
}

/**
 * 填充表单数据
 */
function populateForm(requirement) {
    if (elements.title) elements.title.value = requirement.title || '';
    if (elements.projectId) elements.projectId.value = requirement.projectId || '';
    if (elements.priority) elements.priority.value = requirement.priority || '';
    if (elements.ownerId) elements.ownerId.value = requirement.ownerId || '';
    if (elements.expectedCompletionDate) {
        elements.expectedCompletionDate.value = requirement.expectedCompletionDate ? 
            requirement.expectedCompletionDate.split('T')[0] : '';
    }
    if (elements.description) elements.description.value = requirement.description || '';
    
    // 重置脏标记
    isDirty = false;
}

/**
 * 渲染文档列表
 */
function renderDocuments() {
    if (!elements.documentsList) return;
    
    // 更新文档数量
    if (elements.documentCount) {
        elements.documentCount.textContent = documents.length;
    }
    
    if (documents.length === 0) {
        // 显示空状态
        if (elements.noDocuments) {
            elements.noDocuments.style.display = 'block';
        }
        elements.documentsList.innerHTML = '';
        return;
    }
    
    // 隐藏空状态
    if (elements.noDocuments) {
        elements.noDocuments.style.display = 'none';
    }
    
    // 渲染文档列表
    const documentsHtml = documents.map(doc => createDocumentHtml(doc)).join('');
    elements.documentsList.innerHTML = documentsHtml;
}

/**
 * 创建文档HTML
 */
function createDocumentHtml(doc) {
    const createdAt = doc.createdAt ? formatDate(new Date(doc.createdAt)) : '刚刚添加';
    const description = doc.description ? escapeHtml(doc.description) : '无描述';
    
    return `
        <div class="document-item border rounded p-3 mb-3" data-document-id="${doc.id || doc.tempId}">
            <div class="d-flex justify-content-between align-items-start">
                <div class="flex-grow-1">
                    <h6 class="mb-2">
                        <i class="bi bi-file-earmark-text text-primary me-2"></i>
                        <a href="${escapeHtml(doc.url)}" target="_blank" class="text-decoration-none">
                            ${escapeHtml(doc.title)}
                        </a>
                    </h6>
                    <p class="text-muted mb-2 small">${description}</p>
                    <small class="text-muted">
                        <i class="bi bi-clock me-1"></i>
                        添加于 ${createdAt}
                    </small>
                </div>
                <div class="ms-3">
                    <button type="button" class="btn btn-sm btn-outline-danger delete-document-btn" 
                            onclick="removeDocument('${doc.id || doc.tempId}')" title="删除文档">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
}

/**
 * 显示添加文档模态框
 */
function showAddDocumentModal() {
    if (!elements.addDocumentModal) return;
    
    // 重置表单
    if (elements.addDocumentForm) {
        elements.addDocumentForm.reset();
    }
    
    // 显示模态框
    const modal = bootstrap.Modal.getInstance(elements.addDocumentModal) || 
                  new bootstrap.Modal(elements.addDocumentModal);
    modal.show();
}

/**
 * 保存文档
 */
function saveDocument() {
    try {
        const formData = getDocumentFormData();
        if (!validateDocumentForm(formData)) {
            return;
        }
        
        // 生成临时ID
        const tempId = 'temp_' + Date.now();
        const document = {
            tempId: tempId,
            ...formData
        };
        
        // 添加到文档列表
        documents.push(document);
        
        // 重新渲染文档列表
        renderDocuments();
        
        // 标记表单为脏
        markFormAsDirty();
        
        // 隐藏模态框
        const modal = bootstrap.Modal.getInstance(elements.addDocumentModal);
        if (modal) {
            modal.hide();
        }
        
        showSuccess('文档添加成功');
        
    } catch (error) {
        console.error('保存文档失败:', error);
        showError('保存文档失败: ' + error.message);
    }
}

/**
 * 获取文档表单数据
 */
function getDocumentFormData() {
    return {
        title: document.getElementById('documentTitle')?.value?.trim() || '',
        url: document.getElementById('documentUrl')?.value?.trim() || '',
        description: document.getElementById('documentDescription')?.value?.trim() || ''
    };
}

/**
 * 验证文档表单
 */
function validateDocumentForm(data) {
    if (!data.title) {
        showError('请输入文档标题');
        return false;
    }
    
    if (!data.url) {
        showError('请输入文档链接');
        return false;
    }
    
    if (!isValidUrl(data.url)) {
        showError('请输入有效的URL');
        return false;
    }
    
    return true;
}

/**
 * 编辑文档
 */
function editDocument(documentId) {
    // TODO: 实现编辑文档功能
    console.log('编辑文档:', documentId);
    showInfo('编辑文档功能开发中...');
}

/**
 * 删除文档
 */
function removeDocument(documentId) {
    if (!confirm('确定要删除这个文档吗？')) {
        return;
    }
    
    // 从文档列表中移除
    documents = documents.filter(doc => (doc.id || doc.tempId) !== documentId);
    
    // 重新渲染文档列表
    renderDocuments();
    
    // 标记表单为脏
    markFormAsDirty();
    
    showSuccess('文档删除成功');
}

/**
 * 处理表单提交
 */
async function handleFormSubmit(e) {
    e.preventDefault();
    
    if (!isFormValid(true)) {
        return;
    }
    
    try {
        showLoading(true);
        
        const formData = getFormData();
        
        let response;
        if (isEditMode) {
            response = await fetch(`/api/requirements/${currentRequirementId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });
        } else {
            response = await fetch('/api/requirements', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });
        }
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const result = await response.json();
        
        // 保存文档
        if (documents.length > 0) {
            await saveDocuments(result.id);
        }
        
        // 重置脏标记
        isDirty = false;
        
        showSuccess(isEditMode ? '需求更新成功' : '需求创建成功');
        
        // 跳转到需求详情页
        setTimeout(() => {
            window.location.href = `/requirements/detail?id=${result.id}`;
        }, 1500);
        
    } catch (error) {
        console.error('提交表单失败:', error);
        showError('提交失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

/**
 * 保存文档到服务器
 */
async function saveDocuments(requirementId) {
    const unsavedDocuments = documents.filter(doc => !doc.id);
    
    for (const doc of unsavedDocuments) {
        try {
            const response = await fetch(`/api/requirements/${requirementId}/documents`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title: doc.title,
                    type: doc.type,
                    url: doc.url,
                    description: doc.description
                })
            });
            
            if (!response.ok) {
                console.warn('保存文档失败:', doc.title);
            }
        } catch (error) {
            console.warn('保存文档失败:', error);
        }
    }
}

/**
 * 获取表单数据
 */
function getFormData() {
    const formData = {
        title: elements.title?.value?.trim() || '',
        priority: elements.priority?.value || '',
        description: elements.description?.value?.trim() || ''
    };
    
    // 创建模式下包含项目ID和负责人
    if (!isEditMode) {
        formData.projectId = elements.projectId?.value || null;
        formData.ownerId = elements.ownerId?.value || null;
        formData.expectedCompletionDate = elements.expectedCompletionDate?.value || null;
        formData.status = 'DRAFT';
    }
    
    return formData;
}

/**
 * 验证表单
 */
function isFormValid(showErrors = true) {
    const errors = [];
    
    // 验证必填字段
    if (!elements.title?.value?.trim()) {
        errors.push('请输入需求标题');
    }
    
    if (!elements.projectId?.value) {
        errors.push('请选择所属项目');
    }
    
    if (!elements.priority?.value) {
        errors.push('请选择优先级');
    }
    
    if (!elements.description?.value?.trim()) {
        errors.push('请输入需求描述');
    }
    
    // 验证日期
    if (elements.expectedCompletionDate?.value) {
        const selectedDate = new Date(elements.expectedCompletionDate.value);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        if (selectedDate < today) {
            errors.push('期望完成日期不能早于今天');
        }
    }
    
    if (errors.length > 0 && showErrors) {
        showError(errors.join('\n'));
    }
    
    return errors.length === 0;
}

/**
 * 保存草稿
 */
// saveDraft函数已移除

// showPreview和generatePreviewHtml函数已移除

// submitFromPreview和handleCancel函数已移除

/**
 * 标记表单为脏
 */
function markFormAsDirty() {
    isDirty = true;
    updateStatusDisplay();
}

/**
 * 更新状态显示
 */
function updateStatusDisplay() {
    if (elements.formStatus) {
        if (isDirty) {
            elements.formStatus.textContent = '有未保存更改';
            elements.formStatus.className = 'status-value text-warning';
        } else {
            elements.formStatus.textContent = isEditMode ? '已保存' : '草稿';
            elements.formStatus.className = 'status-value text-success';
        }
    }
    
    if (elements.lastSaved) {
        if (lastSavedTime) {
            elements.lastSaved.textContent = formatDateTime(lastSavedTime);
        } else {
            elements.lastSaved.textContent = '未保存';
        }
    }
}

// 快捷操作函数
function loadTemplate() {
    showInfo('从模板创建功能开发中...');
}

function importDocuments() {
    showInfo('批量导入文档功能开发中...');
}

function exportDraft() {
    showInfo('导出草稿功能开发中...');
}

// 工具函数
function getDocumentTypeText(type) {
    const typeMap = {
        'SPECIFICATION': '需求规格',
        'DESIGN': '设计文档',
        'PROTOTYPE': '原型设计',
        'REFERENCE': '参考资料',
        'OTHER': '其他'
    };
    return typeMap[type] || type;
}

function getDocumentTypeClass(type) {
    const classMap = {
        'SPECIFICATION': 'type-specification',
        'DESIGN': 'type-design',
        'PROTOTYPE': 'type-prototype',
        'REFERENCE': 'type-reference',
        'OTHER': 'type-other'
    };
    return classMap[type] || 'type-other';
}

function getPriorityText(priority) {
    const priorityMap = {
        'LOW': '低',
        'MEDIUM': '中',
        'HIGH': '高',
        'URGENT': '紧急'
    };
    return priorityMap[priority] || priority;
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

function formatDateTime(date) {
    if (!date) return '';
    if (typeof date === 'string') {
        date = new Date(date);
    }
    return date.toLocaleString('zh-CN');
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (_) {
        return false;
    }
}

function showLoading(show) {
    if (!elements.loadingOverlay) return;
    
    if (show) {
        elements.loadingOverlay.classList.remove('d-none');
    } else {
        elements.loadingOverlay.classList.add('d-none');
    }
}

function showSuccess(message) {
    if (!elements.successToast || !elements.successMessage) return;
    
    elements.successMessage.textContent = message;
    const toast = bootstrap.Toast.getInstance(elements.successToast) || 
                  new bootstrap.Toast(elements.successToast);
    toast.show();
}

function showError(message) {
    if (!elements.errorToast || !elements.errorMessage) return;
    
    elements.errorMessage.textContent = message;
    const toast = bootstrap.Toast.getInstance(elements.errorToast) || 
                  new bootstrap.Toast(elements.errorToast);
    toast.show();
}

function showInfo(message) {
    if (!elements.infoToast || !elements.infoMessage) return;
    
    elements.infoMessage.textContent = message;
    const toast = bootstrap.Toast.getInstance(elements.infoToast) || 
                  new bootstrap.Toast(elements.infoToast);
    toast.show();
}